#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
手动记账对话框
"""

import sys
from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QFormLayout, 
                             QLineEdit, QComboBox, QPushButton, QLabel, 
                             QDateTimeEdit, QTextEdit, QMessageBox)
from PyQt5.QtCore import QDateTime, Qt
from database import Database
import sqlite3


class TransactionDialog(QDialog):
    """手动记账对话框"""
    
    def __init__(self, parent=None, db=None):
        super().__init__(parent)
        self.setWindowTitle("添加交易")
        self.setModal(True)
        self.resize(400, 300)
        # 初始化数据库连接
        self.db = db or Database()
        self.setup_ui()
        
    def setup_ui(self):
        """设置界面"""
        layout = QVBoxLayout()
        
        # 表单布局
        form_layout = QFormLayout()
        
        # 交易时间
        self.datetime_edit = QDateTimeEdit()
        self.datetime_edit.setDateTime(QDateTime.currentDateTime())
        self.datetime_edit.setDisplayFormat("yyyy-MM-dd HH:mm")
        self.datetime_edit.setCalendarPopup(True)
        form_layout.addRow("交易时间:", self.datetime_edit)
        
        # 交易类型
        self.type_combo = QComboBox()
        self.type_combo.addItems(["支出", "收入", "转账"])
        form_layout.addRow("交易类型:", self.type_combo)
        
        # 金额
        self.amount_edit = QLineEdit()
        self.amount_edit.setPlaceholderText("请输入金额")
        form_layout.addRow("金额:", self.amount_edit)
        
        # 一级分类
        self.category_combo = QComboBox()
        # 获取分类树
        self.category_tree = self.db.get_category_tree()
        # 填充一级分类
        primary_categories = [category['name'] for category in self.category_tree]
        self.category_combo.addItems(primary_categories)
        form_layout.addRow("一级分类:", self.category_combo)
        
        # 二级分类
        self.subcategory_combo = QComboBox()
        # 连接一级分类变化信号
        self.category_combo.currentIndexChanged.connect(self.update_subcategories)
        # 初始化二级分类
        self.update_subcategories(0)
        form_layout.addRow("二级分类:", self.subcategory_combo)
        
        # 对方/收款人
        self.payee_edit = QLineEdit()
        self.payee_edit.setPlaceholderText("请输入对方/收款人")
        form_layout.addRow("对方/收款人:", self.payee_edit)
        
        # 备注
        self.note_edit = QTextEdit()
        self.note_edit.setMaximumHeight(60)
        form_layout.addRow("备注:", self.note_edit)
        
        layout.addLayout(form_layout)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        self.ok_button = QPushButton("确定")
        self.cancel_button = QPushButton("取消")
        
        self.ok_button.clicked.connect(self.accept)
        self.cancel_button.clicked.connect(self.reject)
        
        button_layout.addStretch()
        button_layout.addWidget(self.ok_button)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
        
    def update_subcategories(self, index):
        """根据一级分类的选择更新二级分类下拉框"""
        # 清空二级分类下拉框
        self.subcategory_combo.clear()
        
        # 如果有选中的一级分类且存在分类树
        if index >= 0 and index < len(self.category_tree):
            # 获取选中的一级分类的二级分类
            subcategories = self.category_tree[index].get('subcategories', [])
            # 填充二级分类下拉框
            subcategory_names = [subcategory['name'] for subcategory in subcategories]
            self.subcategory_combo.addItems(subcategory_names)
        
    def get_transaction_data(self):
        """获取交易数据"""
        timestamp = self.datetime_edit.dateTime().toString("yyyy-MM-ddTHH:mm:ss")
        trans_type = self.type_combo.currentText()
        amount = float(self.amount_edit.text())
        category = self.category_combo.currentText()
        subcategory = self.subcategory_combo.currentText()
        # 构造分类字符串，格式为"一级分类|二级分类"
        if subcategory:
            category = f"{category}|{subcategory}"
        payee = self.payee_edit.text()
        note = self.note_edit.toPlainText()
        
        return Transaction(
            timestamp=timestamp,
            amount=amount,
            type=trans_type,
            category=category,
            payee=payee,
            source="手动",
            note=note
        )
        
    def accept(self):
        """确认按钮事件"""
        # 获取表单数据
        timestamp = self.datetime_edit.dateTime().toString('yyyy-MM-dd HH:mm:ss')
        amount = self.amount_edit.text()
        type = self.type_combo.currentText()
        category = self.category_combo.currentText()
        subcategory = self.subcategory_combo.currentText()
        # 构造分类字符串，格式为"一级分类|二级分类"
        if subcategory:
            category = f"{category}|{subcategory}"
        payee = self.payee_edit.text()
        source = "手动"  # 默认为手动添加
        note = self.note_edit.toPlainText()
        
        # 数据验证
        if not amount:
            QMessageBox.warning(self, '输入错误', '金额不能为空')
            return
            
        try:
            amount = float(amount)
        except ValueError:
            QMessageBox.warning(self, '输入错误', '金额必须是数字')
            return
            
        if amount <= 0:
            QMessageBox.warning(self, '输入错误', '金额必须大于0')
            return
            
        # 保存到数据库
        try:
            self.db.insert_transaction(timestamp, amount, type, category, payee, source, note)
            super().accept()
        except Exception as e:
            QMessageBox.critical(self, '保存失败', f'保存交易记录时出错: {str(e)}')